#!/bin/bash

replace_ip(){
  sed -ri 's/(\b[0-9]{1,3}\.){3}[0-9]{1,3}\b'/$1/ $2
  echo $1 >> /etc/ansible/hosts
}

check_input_para(){
  echo $1|grep "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" > /dev/null
  if [ $? = 0 ]; then
    return 0
  else
    return 1
  fi
}

chang_ali_source(){
	cd /etc/yum.repos.d
	if [ -f "CentOS-AppStream.repo.bak" ]; then
		echo ""
	else
		mv CentOS-AppStream.repo CentOS-AppStream.repo.bak
		wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-8.repo
		yum makecache
		sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo	
	fi
}

install_ansible(){
  rpm -q ansible
  if [ $? = 0 ]; then
    return 0
  else
    dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm -y
    dnf install ansible -y
    echo "[k8snode]" >> /etc/ansible/hosts
    grep interpreter_python /etc/ansible/ansible.cfg
    if [ $? -eq 1 ]; then
      sed -i '/\[defaults\]/a\interpreter_python = /usr/bin/python3' /etc/ansible/ansible.cfg
    fi
  fi
}

copy_ssh_id(){
  cd
  if [ -f ".ssh/id_rsa.pub" ]; then
    ssh-copy-id -i .ssh/id_rsa.pub root@$1 
  else
    ssh-keygen -t rsa
    ssh-copy-id -i .ssh/id_rsa.pub root@$1
  fi
}

if [ $# -eq 1 ]; then
  src_path=`pwd`
  check_input_para $1
  if [ $? = 0 ]; then
    echo "input ip addr ok"
  else
    echo "ip addr error"
    exit
  fi

  chang_ali_source
  install_ansible
  copy_ssh_id $1
  cd $src_path
  echo "Please choose from the following options"
  echo -e "\t1:install docker"
  echo -e "\t2:install kubernetes master"
  echo -e "\t3:install kubernetes node"
  echo -n "Enter your do what:"
  read option

  if [ $option -eq 1 ]; then
    #echo "ansible-playbook ./install-docker.yml"
    replace_ip $1 "./install-docker.yml"
    ansible-playbook ./install-docker.yml
  elif [ $option -eq 2 ]; then
    #echo "ansible-playbook ./install-k8s-master.yml"
    replace_ip $1 "./install-k8s-master.yml"
    ansible-playbook ./install-k8s-master.yml
  elif [ $option -eq 3 ]; then
    #echo "ansible-playbook ./install-k8s-node.yml"
    replace_ip $1 "./install-k8s-node.yml"
    ansible-playbook ./install-k8s-node.yml
  else
    echo "choose error"
    exit;
  fi
else
  echo "sh do.sh ip_addr"
fi
